<?php
/***************************************************************************
*                            Dolphin Smart Community Builder
*                              -------------------
*     begin                : Mon Mar 23 2006
*     copyright            : (C) 2007 BoonEx Location
*     website              : http://www.boonex.com
* This file is part of Dolphin - Smart Community Builder
*
* Dolphin is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the
* License, or  any later version.
*
* Dolphin is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with Dolphin,
* see license.txt file; if not, write to marketing@boonex.com
***************************************************************************/

bx_import('BxDolTwigPageView');

class BxLocationPageView extends BxDolTwigPageView {	

	function BxLocationPageView(&$oMain, &$aDataEntry) {
		parent::BxDolTwigPageView('modzzz_location_view', $oMain, $aDataEntry);
	
        $this->sSearchResultClassName = 'BxLocationSearchResult';
        $this->sFilterName = 'modzzz_location_filter';

        $this->sUrlStart = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/'. $this->aDataEntry['uri'];
        $this->sUrlStart .= (false === strpos($this->sUrlStart, '?') ? '?' : '&');  
 
		switch($_GET['ajax']) {  
			case 'delete_review':
				$iLocationId = $_GET['id'];
				$iReviewId = $_GET['review'];
				$this->_oDb->DeleteReview($iLocationId, $iReviewId); 
				echo '';
				exit;
			break; 
		}	

	}

	function getBlockCode_Share() {  
 
		$aVars = array (
		    'site_url' => $this->sUrlStart,
			'width' => getParam('modzzz_location_facebook_app_width')
		);
		return $this->_oTemplate->parseHtmlByName('block_social_share', $aVars);	 
	}

	function getBlockCode_FacebookComments() {  
 
		if(!getParam('modzzz_location_facebook_app_key'))
			return;

		$aVars = array (
		    'app_id' => getParam('modzzz_location_facebook_app_key'),
			'width' => getParam('modzzz_location_facebook_app_width')
		);
		return $this->_oTemplate->parseHtmlByName('block_facebook_comments', $aVars);	 
	}

    /**
     * Profile block with user's location map
     * @param $iEntryId user's id which location is shown on the map
     * @return html with user's location map
     */         
  	function getBlockCode_Map() {

        $iEntryId = (int)$this->aDataEntry['id'];   
		$iAuthorId = (int)$this->aDataEntry['author_id'];   
	 
        $r = $this->_oDb->getProfileById($iEntryId);

        $sBoxContent = '';
        if ($r && $this->_oMain->isAllowedViewLocation ($iEntryId, $r)) {
   
			$sBaseUri = BX_DOL_URL_ROOT . $this->_oMain->_oConfig->getBaseUri();
 
			$this->_oTemplate->addInjection('injection_body', 'text',  'onload="load(\''.$sBaseUri.'\', '.$this->aDataEntry['id'].', '.$r['lat'].', '.$r['lng'].');"'); 
			$this->_oTemplate->addJs ('http://maps.google.com/maps/api/js?sensor=false');
			$this->_oTemplate->addJs ('gmap_single.js');
 
            $aVars = array (
                'text' => $r['address'] ? $r['address'] : _t('_modzzz_location_the_same_address'), 
            );
            $sBoxContent = $this->_oTemplate->parseHtmlByName('block_map_single', $aVars);
		 
			//$sBoxStreet = $this->_oTemplate->parseHtmlByName('block_map_street_single', $arr=array());
		}

/*
		$sBoxFooter = '';
		if ($this->_oMain->isAdmin() || $this->_oMain->isEntryAdmin($this->aDataEntry)) {
			$aVars = array (
				'icon' => $this->_oTemplate->getIconUrl('more.png'),
				'url' => $this->_oConfig->getBaseUri() . "map_edit/{$iEntryId}",
				'title' => _t('_modzzz_location_box_footer_edit'),
			);
			$sBoxFooter = $this->_oTemplate->parseHtmlByName('box_footer', $aVars);
			if (!$sBoxContent)
				$sBoxContent = MsgBox(_t('_modzzz_location_msg_locations_is_not_defined'));
		}
*/
 

		if ($sBoxContent || $sBoxFooter)
			return array($sBoxContent, array(), $sBoxFooter);
		return '';

	}
 
	function getBlockCode_Review() { 
		$iEntryId = $this->aDataEntry['id'];
 
		$iLimit = $this->_oDb->getParam('modzzz_location_perpage_review');
		$sUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $this->aDataEntry['uri'];
  
		$iCount = $this->_oDb->getReviewCount($iEntryId);  

		if(!$iCount)
			return;

        $sPaginate = ''; 
        if ($iCount) {
            $iPages = ceil($iCount/ $iLimit);
            $iPage = ( isset($_GET['page']) ) ? (int) $_GET['page'] : 1;

            if ( $iPage < 1 ) {
                $iPage = 1;
            }
            if ( $iPage > $iPages ) {
                $iPage = $iPages;
            }    

            $sqlFrom = ($iPage - 1) * $iLimit;
            $sqlLimit = "LIMIT {$sqlFrom}, {$iLimit}";  
		}
		$aAllEntries = $this->_oDb->getReviews($iEntryId, $sqlLimit);
 
		$aVars = array (
			'bx_repeat:review' => array (),
		);
  
		foreach($aAllEntries as $aEntry)
		{ 
			$iReviewId = (int)$aEntry['id'];
			$iLocationId = (int)$aEntry['location_id'];
			$iSubId = (int)$aEntry['sub_id'];
			$iMemberId = $aEntry['member_id'];
			$sNickName = getNickName($iMemberId);
			$sNickLink = getProfileLink($iMemberId);
			$icoMember = get_member_thumbnail($iMemberId, 'left');
			$sMessage = $aEntry['desc']; 
			$dtSent = date("M jS, Y g:i A", $aEntry['created']);
		 
			$sType = $aEntry['type'];
			if($sType=='location'){
				$aLocation = $this->_oDb->getEntryById($iLocationId);
				
				$sLocationName = $aLocation['title'];
				$sLocationUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aLocation['uri'];
			}else{
				$aSubProfile = $this->_oDb->getSubProfileEntryById($sType, $iSubId);
				$aLocation = $this->_oDb->getEntryById($iLocationId);
				
				$sLocationName = $aSubProfile['title'];
				$sLocationUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . $sType .'/view/' . $aSubProfile['uri'];
			}


			$bAdmin = $this->_oMain->isEntryAdmin($this->aDataEntry) || ($iMemberId==$this->_oMain->_iProfileId);

			$aVars['bx_repeat:review'][] = array (
				'entry_id' => $iEntryId, 
				'review_id' => $iReviewId, 
				'ico_member' => $icoMember, 
				'nicklink' => $sNickLink,
				'nickname' => $sNickName,
				'date' => $dtSent,
				'message' => $sMessage,
				'location_name' => $sLocationName, 
				'location_url' => $sLocationUrl, 
				'bx_if:allowdelete' => array( 
					'condition' =>  $bAdmin,
					'content' => array(
 						'entry_id' => $iEntryId, 
						'review_id' => $iReviewId, 
						'url' => $sUrl,   
					), 
				),	 

			);  
		} 
  
		$sCode = $this->_oTemplate->parseHtmlByName('block_reviews', $aVars);
	
		if ($iPages > 1) {
		   $oPaginate = new BxDolPaginate(array(
				'page_url' => $sUrl,
				'count' => $iCount,
				'per_page' => $iLimit,
				'page' => $iPage,
				'per_page_changer' => true,
				'page_reloader' => true,
				'on_change_page' => 'return !loadDynamicBlock({id}, \''.$sUrl.'?page={page}&per_page={per_page}\');',
				'on_change_per_page' => ''
			)); 
			
			$sAjaxPaginate = $oPaginate->getSimplePaginate('',-1,-1, false); 
		}   	
  
		return array($sCode, array(), $sAjaxPaginate);
	}

		
	function getBlockCode_Info() {
        return $this->_blockInfo ($this->aDataEntry);
    }

	//override the similar mod in the parent class
    function _blockInfo ($aData) {

        $aAuthor = getProfileInfo($aData['author_id']);
 
		$sAuthorName =  $aAuthor['NickName'];
		$sAuthorLink = getProfileLink($aAuthor['ID']);	
		$icoThumb = get_member_thumbnail($aAuthor['ID'], 'none');
	 
        $aVars = array (
            'author_thumb' => $icoThumb,
            'date' => getLocaleDate($aData['created'], BX_DOL_LOCALE_DATE_SHORT),
            'date_ago' => defineTimeInterval($aData['created']),
			'parent_category' => $this->_oDb->getCategoryName($aData['categories']),
			'category' => $this->_oDb->getCategoryName($aData['category_id']),
			'tags' => $this->_oTemplate->parseTags($aData['tags']),
            'fields' => '',
            'author_username' => $sAuthorName,
            'author_url' => $sAuthorLink,
        );
        return $this->_oTemplate->parseHtmlByName('block_info', $aVars);
    }
 
	function getBlockCode_Desc() {
        return $this->_oTemplate->blockDesc ($this->aDataEntry);
    }
 
	function getBlockCode_Location() {
        return $this->_blockCustomDisplay ($this->aDataEntry, 'location');
    }
  
	function _blockCustomDisplay($aDataEntry, $sType) {
		
		switch($sType)
		{   
			case "location":
				$aAllow = array('address1','address2','city','zip','state','country');
			break;  
		}
  
		$sFields = $this->_oTemplate->blockCustomFields($aDataEntry,$aAllow);

		$aVars = array ( 
            'fields' => $sFields, 
        );

        return $this->_oTemplate->parseHtmlByName('custom_block_info', $aVars);   
    }

	function getBlockCode_VideoEmbed() { 
 
	    $sVideoEmbed = trim($this->aDataEntry['video_embed']);
		
		if(!$sVideoEmbed)
			  return;
		
		$aVars = array ( 
			'embed' => $sVideoEmbed 
	    );
	
	    return $this->_oTemplate->parseHtmlByName('embed_block', $aVars);  
	}

	function getBlockCode_Photo() {
        return $this->_blockPhoto ($this->_oDb->getMediaIds($this->aDataEntry['id'], 'images'), $this->aDataEntry['author_id']);
    }    

    function getBlockCode_Video() {
        return $this->_blockVideo ($this->_oDb->getMediaIds($this->aDataEntry['id'], 'videos'), $this->aDataEntry['author_id']);
    }    

    function getBlockCode_Sound() {
        return $this->_blockSound ($this->_oDb->getMediaIds($this->aDataEntry['id'], 'sounds'), $this->aDataEntry['author_id']);
    }    

    function getBlockCode_Files() {
        return $this->_blockFiles ($this->_oDb->getMediaIds($this->aDataEntry['id'], 'files'), $this->aDataEntry['author_id']);
    }    

    function getBlockCode_Rate() {
        modzzz_location_import('Voting');
        $o = new BxLocationVoting ('modzzz_location', (int)$this->aDataEntry['id']);
        if (!$o->isEnabled()) return '';
        return $o->getBigVoting ($this->_oMain->isAllowedRate($this->aDataEntry));
    }        

    function getBlockCode_Comments() {    
        modzzz_location_import('Cmts');
        $o = new BxLocationCmts ('modzzz_location', (int)$this->aDataEntry['id']);
        if (!$o->isEnabled()) return '';
        return $o->getCommentsFirst ();
    }            

    function getBlockCode_Actions() {
        global $oFunctions;

        if ($this->_oMain->_iProfileId || $this->_oMain->isAdmin()) {

            $oSubscription = new BxDolSubscription();
            $aSubscribeButton = $oSubscription->getButton($this->_oMain->_iProfileId, 'modzzz_location', '', (int)$this->aDataEntry['id']);
			
			$isFan = $this->_oDb->isFan((int)$this->aDataEntry['id'], $this->_oMain->_iProfileId, 0) || $this->_oDb->isFan((int)$this->aDataEntry['id'], $this->_oMain->_iProfileId, 1);

            $aInfo = array (
                'BaseUri' => $this->_oMain->_oConfig->getBaseUri(),
                'iViewer' => $this->_oMain->_iProfileId,
                'ownerID' => (int)$this->aDataEntry['author_id'],
                'ID' => (int)$this->aDataEntry['id'],
                'URI' => $this->aDataEntry['uri'],
                'ScriptSubscribe' => $aSubscribeButton['script'],
                'TitleSubscribe' => $aSubscribeButton['title'], 
                'TitleEdit' => $this->_oMain->isAllowedEdit($this->aDataEntry) ? _t('_modzzz_location_action_title_edit') : '',
                'TitleDelete' => $this->_oMain->isAllowedDelete($this->aDataEntry) ? _t('_modzzz_location_action_title_delete') : '',
                'TitleShare' => $this->_oMain->isAllowedShare($this->aDataEntry) ? _t('_modzzz_location_action_title_share') : '',
				'TitleInvite' => $this->_oMain->isAllowedSendInvitation($this->aDataEntry) ? _t('_modzzz_location_action_title_promote') : '',  
				'TitleReview' => $this->_oMain->isAllowedReview($this->aDataEntry) ? _t('_modzzz_location_action_title_review') : '',
                'TitleHere' => $this->_oMain->isAllowedHere($this->aDataEntry) ? _t('_modzzz_location_action_title_here') : '',
				'TitleBeenHere' => $this->_oMain->isAllowedBeenHere($this->aDataEntry) ? _t('_modzzz_location_action_title_been_here') : '',
                'TitleGoingHere' => $this->_oMain->isAllowedGoingHere($this->aDataEntry) ? _t('_modzzz_location_action_title_going_here') : '',
				'AddToFeatured' => $this->_oMain->isAllowedMarkAsFeatured($this->aDataEntry) ? ($this->aDataEntry['featured'] ? _t('_modzzz_location_action_remove_from_featured') : _t('_modzzz_location_action_add_to_featured')) : '',
 		  
				'TitleEventAdd' => $this->_oMain->isAllowedSubAdd($this->aDataEntry) ? _t('_modzzz_location_action_title_add_event') : '',
 				'TitleHotelAdd' => $this->_oMain->isAllowedSubAdd($this->aDataEntry) ? _t('_modzzz_location_action_title_add_hotel') : '',
				'TitleShopAdd' => $this->_oMain->isAllowedSubAdd($this->aDataEntry) ? _t('_modzzz_location_action_title_add_shop') : '',
				'TitleFoodAdd' => $this->_oMain->isAllowedSubAdd($this->aDataEntry) ? _t('_modzzz_location_action_title_add_food') : '',
				'TitleTransportAdd' => $this->_oMain->isAllowedSubAdd($this->aDataEntry) ? _t('_modzzz_location_action_title_add_transport') : '',
				'TitleNightlifeAdd' => $this->_oMain->isAllowedSubAdd($this->aDataEntry) ? _t('_modzzz_location_action_title_add_nightlife') : '',
				'TitleSchoolAdd' => $this->_oMain->isAllowedSubAdd($this->aDataEntry) ? _t('_modzzz_location_action_title_add_school') : '',
				'TitleServiceAdd' => $this->_oMain->isAllowedSubAdd($this->aDataEntry) ? _t('_modzzz_location_action_title_add_service') : '',

				'TitleUploadPhotos' => $this->_oMain->isAllowedUploadPhotos($this->aDataEntry) ? _t('_modzzz_location_action_upload_photos') : '',
                'TitleUploadVideos' => $this->_oMain->isAllowedUploadVideos($this->aDataEntry) ? _t('_modzzz_location_action_upload_videos') : '',
                'TitleUploadSounds' => $this->_oMain->isAllowedUploadSounds($this->aDataEntry) ? _t('_modzzz_location_action_upload_sounds') : '',
                'TitleUploadFiles' => $this->_oMain->isAllowedUploadFiles($this->aDataEntry) ? _t('_modzzz_location_action_upload_files') : '',
            );

            if (!$aInfo['TitleEdit'] && !$aInfo['TitleDelete'] && !$aInfo['TitleShare'] && !$aInfo['AddToFeatured'] && !$aInfo['TitleUploadPhotos'] && !$aInfo['TitleUploadVideos'] && !$aInfo['TitleUploadSounds'] && !$aInfo['TitleUploadFiles']) 
                return '';

            return $oSubscription->getData() . $oFunctions->genObjectsActions($aInfo, 'modzzz_location');
        } 

        return '';
    }    
 
	function getBlockCode_Local() {    
		return $this->ajaxBrowse('local', $this->_oDb->getParam('modzzz_location_perpage_main_recent'),array(),$this->aDataEntry['city'],$this->aDataEntry['id']); 
	}

	function getBlockCode_Other() {    
		return $this->ajaxBrowse('other', $this->_oDb->getParam('modzzz_location_perpage_main_recent'),array(),$this->aDataEntry['author_id'],$this->aDataEntry['id']); 
	}

    function ajaxBrowse($sMode, $iPerPage, $aMenu = array(), $sValue = '', $sValue2 = '', $isDisableRss = false, $isPublicOnly = true) {
        $oMain = BxDolModule::getInstance('BxLocationModule');

        bx_import ('SearchResult', $oMain->_aModule);
        $sClassName = $this->sSearchResultClassName;
        $o = new $sClassName($sMode, $sValue, $sValue2);
        $o->aCurrent['paginate']['perPage'] = $iPerPage; 
        $o->setPublicUnitsOnly($isPublicOnly);

        if (!$aMenu)
            $aMenu = ($isDisableRss ? '' : array(_t('RSS') => array('href' => $o->aCurrent['rss']['link'] . (false === strpos($o->aCurrent['rss']['link'], '?') ? '?' : '&') . 'rss=1', 'icon' => getTemplateIcon('rss.png'))));

        if ($o->isError)
            return array(MsgBox(_t('_Error Occured')), $aMenu);

        if (!($s = $o->displayResultBlock())) 
            return $isPublicOnly ? array(MsgBox(_t('_Empty')), $aMenu) : '';


        $sFilter = (false !== bx_get($this->sFilterName)) ? $this->sFilterName . '=' . bx_get($this->sFilterName) . '&' : '';
        $oPaginate = new BxDolPaginate(array(
            'page_url' => 'javascript:void(0);',
            'count' => $o->aCurrent['paginate']['totalNum'],
            'per_page' => $o->aCurrent['paginate']['perPage'],
            'page' => $o->aCurrent['paginate']['page'],
            'on_change_page' => 'return !loadDynamicBlock({id}, \'' . $this->sUrlStart . $sFilter . 'page={page}&per_page={per_page}\');',
        ));
        $sAjaxPaginate = $oPaginate->getSimplePaginate($this->_oConfig->getBaseUri() . $o->sBrowseUrl);

        return array(
            $s, 
            $aMenu,
            $sAjaxPaginate,
            '');
    }   

	function getBlockCode_Fans() {
		$iID = $this->aDataEntry['id'];
  
		$iLimit = $this->_oDb->getParam('modzzz_location_perpage_view_fans');
		$sUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $this->aDataEntry['uri'];
 

		// top menu and sorting
        $aModes = array('beenhere', 'here', 'goinghere');
        $aDBTopMenu = array();
  
        $sMode = (in_array($_GET['hereMode'], $aModes)) ? $_GET['hereMode'] : $sMode = 'beenhere';
        foreach( $aModes as $sMyMode ) {
            switch ($sMyMode) {
                case 'here': 
                    $sModeTitle = _t('_modzzz_location_here');
                break;
                case 'beenhere': 
                    $sModeTitle = _t('_modzzz_location_been_here');
                break;
                case 'goinghere': 
                    $sModeTitle = _t('_modzzz_location_going_here');
                break; 
            }
            $aDBTopMenu[$sModeTitle] = array('href' => "{$sUrl}?hereMode=$sMyMode", 'dynamic' => true, 'active' => ( $sMyMode == $sMode ));
        }

		$iCount = $this->_oDb->getFanCount($iID, $sMode);  
        $sPaginate = ''; 
        if ($iCount) {
            $iPages = ceil($iCount/ $iLimit);
            $iPage = ( isset($_GET['page']) ) ? (int) $_GET['page'] : 1;

            if ( $iPage < 1 ) {
                $iPage = 1;
            }
            if ( $iPage > $iPages ) {
                $iPage = $iPages;
            }    

            $sqlFrom = ($iPage - 1) * $iLimit;
            $sqlLimit = "LIMIT {$sqlFrom}, {$iLimit}";  
		}  
		$aAllEntries = $this->_oDb->getAllFans($iID, $sMode, $sqlLimit);
 
		$aVars = array (
			'bx_repeat:fan' => array ()
		);
 
		foreach($aAllEntries as $aEntry){ 
		 
			$iMemberId = $aEntry['id_profile'];
			$sNickName = getNickName($iMemberId);
			$sNickLink = getProfileLink($iMemberId);
			$icoMember = get_member_thumbnail($iMemberId, "left");
		 
			$aVars['bx_repeat:fan'][] = array (
				'ico_member' => $icoMember, 
				'nicklink' => $sNickLink,
				'nickname' => $sNickName 
			);  
		}
 
		if(count($aAllEntries)){ 
			$sCode = $this->_oTemplate->parseHtmlByName('block_fans', $aVars);
 		
            if ($iPages > 1) {
			   $oPaginate = new BxDolPaginate(array(
					'page_url' => $sUrl,
					'count' => $iCount,
					'per_page' => $iLimit,
					'page' => $iPage,
					'per_page_changer' => true,
					'page_reloader' => true,
                    'on_change_page' => 'return !loadDynamicBlock({id}, \''.$sUrl.'?hereMode='.$sMode.'&page={page}&per_page={per_page}\');',
					'on_change_per_page' => ''
				)); 
				
				$sAjaxPaginate = $oPaginate->getSimplePaginate('',-1,-1, false); 
            }   	
		
		}else{	
			$sCode = MsgBox(_t("_modzzz_location_no_members_found")) ; 
		}

		return array($sCode, $aDBTopMenu, $sAjaxPaginate);
	}

    function getCode() { 
        return parent::getCode();
    }

}

?>